package TCP回显服务器;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TCPServer {
    ServerSocket serverSocket=null;
    public TCPServer(int port) throws IOException {
        serverSocket=new ServerSocket(port);
    }
    public void start() throws IOException {
        System.out.println("服务器启动成功");
        //等待服务器跟客户端建立连接
        while (true){
            Socket socket=serverSocket.accept();
            //版本1： processConnect(socket);
            //通过processSocket方法建立连接，但是processSocket如果不结束，就无法走到新的循环
            //即一次只能处理一个客户端，于是我们立刻就能想到使用多线程
            /*版本2：多线程
             Thread t=new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        processConnect(socket);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
            thread.start();
            由于客户端是频繁的创建删除，也就是说，线程频繁的创建和删除，我们就可以立刻想到：线程池
            */
            ExecutorService pool= Executors.newCachedThreadPool();
            pool.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        processConnect(socket);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }
    private void processConnect(Socket clientSocket) throws IOException {
        System.out.printf("[%s:%d] 建立连接!\n",clientSocket.getInetAddress().toString(),clientSocket.getPort());
       try(InputStream inputStream=clientSocket.getInputStream(); OutputStream outputStream=clientSocket.getOutputStream()){
           Scanner scanner=new Scanner(inputStream);
           PrintWriter printWriter=new PrintWriter(outputStream);
           while (true){
               if (!scanner.hasNext()){
                   //连接断开的时候，即客户端关闭的时候，就读到了EOF，于是这里也就返回了false
                   System.out.printf("[%s:%d] 断开连接!\n",clientSocket.getInetAddress().toString(),clientSocket.getPort());
                   break;
               }
               //读取请求
               String request=scanner.next();
               //解析请求，构造响应
               String response=process(request);
               //返回响应
               printWriter.println(response);
               //刷新缓冲区
               printWriter.flush();
               System.out.printf("[%s:%d] request:%s;response:%s\n",clientSocket.getInetAddress().toString(),clientSocket.getPort(),request,response);
           }
       }finally {
           //客户端请求完后需要关闭资源
           clientSocket.close();
       }
    }
    public String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TCPServer tcpServer=new TCPServer(8000);
        tcpServer.start();
    }
}
